package cdu.notFound.controller;

import cdu.notFound.model.User;
import cdu.notFound.service.UserService;
import cdu.notFound.service.impl.UserServiceImpl;
import cdu.notFound.utils.LoginVerify;
import cdu.notFound.utils.MD5;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户信息修改更新
 */
@WebServlet("/UpdateUserInfoServlet")
public class UpdateUserInfoServlet extends HttpServlet {
    private String getNotNullParameter(HttpServletRequest request,String s){
    	return request.getParameter(s)==null?"":request.getParameter(s);
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    //验证更新信息并写入数据库
		Boolean isLogin= LoginVerify.isLogin(request);//判断是否已经登录
		String info="";
		if(isLogin){
			//已经登录，获取用户信息参数
			User user=(User)(request.getSession().getAttribute("loginUser"));
			String name=getNotNullParameter(request,"name");
			String phone=getNotNullParameter(request,"phone");
			String pwd1=getNotNullParameter(request,"pwd1");
			String pwd2=getNotNullParameter(request,"pwd2");
			String address = getNotNullParameter(request,"address");
			if(pwd1.length()>0){
				if(pwd1.equals(pwd2) && pwd1.matches("[A-Za-z0-9]{6,}")){
					user.setPwd(MD5.getMD5(pwd1));
				}else{
					info="更新失败，两次密码不一致";
					response.sendRedirect("user/personal.jsp?tab=info&info="+java.net.URLEncoder.encode(info,"UTF-8"));
					return;
				}
			}
			if(name.length()>0 && (phone.matches("^[0-9]*$") || phone.length()==0)){
				user.setName(name);
				user.setPhone(phone);
				user.setAddress(address);
				UserService userService = new UserServiceImpl();
				if(userService.doUpdate(user)){
					info="更新信息成功";
				}else{
					info="更新失败";
				}
			}else{
				info="更新失败，检查你的输入";
			}
			response.sendRedirect("user/personal.jsp?tab=info&info="+java.net.URLEncoder.encode(info,"UTF-8"));
		}else{
			response.sendRedirect("user/login.jsp?login-info="+java.net.URLEncoder.encode("你应该先登录","UTF-8"));
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    doGet(request, response);
	}

}
